//
//  ImagePickerCell.m
//  Common
//
//  Created by shiqing guo on 2018/6/2.
//  Copyright © 2018年 www.bitkinetic.com. All rights reserved.
//

#import "ImagePickerCell.h"
#import "ToastView.h"
#import "Url.h"
#import "IQMediaPickerController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "FileService.h"
//#import "EditAvatarVC.h"
#import "LYLPhotoTailoringViewController.h"
#import "Message.h"

@interface ImagePickerCell ()<IQMediaPickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, PhotoViewControllerDelegate>
{
    UIImagePickerControllerSourceType _photoType;
}

@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) IQMediaPickerController *IQPiker;
@property (nonatomic, strong) FileService *fileService;

@property (nonatomic, strong) UIImage *img;
@property (nonatomic, copy) NSString *imgName;
@end

@implementation ImagePickerCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.frame = frame;
        
        WEAKSELF
        [self.fileService registerSuccessBlock:^(NSString *key, NSString *domain){
            weakSelf.returnImageUrl(key, domain);
            NSLog(@"imageUrl = %@/%@", domain, key);
            if (weakSelf.parentVC) {
                [weakSelf.parentVC hideProcessingHud_Modal];
            } else {
                [weakSelf.parentTVC hideProcessingHud_Modal];
            }
            [ToastView showMsg:NSLocalizedString(@"UpLoadSuccess", @"上传成功") inView:weakSelf.navC.topViewController.view];
            if ([weakSelf respondsToSelector:@selector(returnImage:)]) {
                [weakSelf returnImage:weakSelf.img];
            }
        } WithProgressBlock:^(float progress) {
            NSLog(@"%.2f", progress);
        } WithFailureBlock:^(NSString *message){
            if (weakSelf.parentVC) {
                [weakSelf.parentVC hideProcessingHud_Modal];
            } else {
                [weakSelf.parentTVC hideProcessingHud_Modal];
            }
            [ToastView showMsg:NSLocalizedString(@"UpLoadFailed", @"上传失败") inView:weakSelf.navC.topViewController.view];
        }];
        [self addSubviews];
    }
    return self;
}

- (void)addSubviews
{
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.bottomLineHidden = YES;
}

- (void)upDataImageToService
{
    if (self.parentVC) {
        [self.parentVC showProcessingHud_Modal:NSLocalizedString(@"UpLoading", @"上传中")];
    } else {
        [self.parentTVC showProcessingHud_Modal:NSLocalizedString(@"UpLoading", @"上传中")];
    }
    [self.fileService sendFileWithImage:self.img andImageName:self.imgName andModuleType:EPModule1 andFileType:self.fileType];
}

#pragma mark - 懒加载
- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.navigationBar.barStyle = UIBarStyleDefault;
        _imagePicker.navigationBar.translucent = NO;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (IQMediaPickerController *)IQPiker
{
    if (!_IQPiker) {
        _IQPiker = [[IQMediaPickerController alloc] init];
        _IQPiker.delegate = self;
        [_IQPiker setMediaType:IQMediaPickerControllerMediaTypePhotoLibrary];
        _IQPiker.allowsPickingMultipleItems = YES;
        _IQPiker.maximumNumberOfSelection = 1;
        _IQPiker.isShowAlert = YES;
        _IQPiker.isReverseOrder = NO;
        _IQPiker.maxImageSize = CGSizeMake(640, 640);
        _IQPiker.isGotoPickDetail = YES;
    }
    return _IQPiker;
}

- (FileService *)fileService
{
    if (!_fileService) {
        _fileService = [[FileService alloc] init];
    }
    return _fileService;
}

#pragma mark - Action
- (void)showImageChooseActionSheet
{
    NSString *strPhoneTitle = NSLocalizedString(@"PhotoSelectType_Phone", @"拍摄");
    NSString *strAlbumTitle = NSLocalizedString(@"PhotoSelectType_Album", @"从手机相册上传");
    NSString *strDefault = NSLocalizedString(@"CM_MyCustomers_Placeholder3", @"使用默认头像");
//    NSString *strCloudTitle = NSLocalizedString(@"PhotoSelectType_Cloud", @"从云盘上传");
    NSArray *arr = [NSArray array];
    if ([self.fileType isEqualToString:@""]) {
        arr = @[strDefault, strAlbumTitle];
    } else {
        arr = @[strPhoneTitle, strAlbumTitle];
    }
    WEAKSELF
    [self showAlertWithItemNameList:arr withBlock:^(NSUInteger index, NSString * _Nonnull itemName) {
        if (0 == index) {
            if ([weakSelf.fileType isEqualToString:@""]) {
                [weakSelf chooseDefaultImage];
            } else {
                [weakSelf phoneActivity];
            }
        }
        else if (1 == index) {
            [weakSelf albumActivity];
        }
    }];
}

- (void)showAlertWithItemNameList:(NSArray <NSString *> *)nameList withBlock:(void (^ __nullable)(NSUInteger index, NSString *itemName))block
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (int i = 0; i < nameList.count; ++i) {
        NSString *itemName = [nameList objectAtIndex:i];
        UIAlertAction *action = [UIAlertAction actionWithTitle:itemName style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSUInteger index = [nameList indexOfObject:action.title];
            block(index, action.title);
        }];
        [action setValue:[EPColor epColor_Blue] forKey:@"titleTextColor"];
        [alertController addAction:action];
    }
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [cancleAction setValue:[EPColor epColor_Blue] forKey:@"titleTextColor"];
    [alertController addAction:cancleAction];
    
    // 解决ipad闪退问题
    if ([alertController respondsToSelector:@selector(popoverPresentationController)]) {
        alertController.popoverPresentationController.sourceView = self.navC.view;
    }
    [self.navC presentViewController:alertController animated:YES completion:nil];
}

- (void)phoneActivity
{
    WEAKSELF
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted) {
            MainQueue(^{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    weakSelf.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                }
                weakSelf.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                [weakSelf presentChooseImageVC:weakSelf.imagePicker];
            });
        } else {  //未授权：
            //返回主线程处理：
            MainQueue(^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:MSG_NO_PERMIT_CAMERA preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", @"确定") style:UIAlertActionStyleCancel handler:nil];
                [alert addAction:cancelAction];
                
                // 解决ipad闪退问题
                if ([alert respondsToSelector:@selector(popoverPresentationController)]) {
                    alert.popoverPresentationController.sourceView = weakSelf.navC.view;
                }
                [weakSelf.navC presentViewController:alert animated:YES completion:nil];
            });
        }
    }];
}

- (void)albumActivity
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
    {
        //无权限
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:MSG_NO_PERMIT_Photo preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", @"确定") style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        
        // 解决ipad闪退问题
        if ([alert respondsToSelector:@selector(popoverPresentationController)]) {
            alert.popoverPresentationController.sourceView = self.navC.view;
        }
        [self.navC presentViewController:alert animated:YES completion:nil];
        return;
    }
    // 解决ipad闪退问题
    if ([self.IQPiker respondsToSelector:@selector(popoverPresentationController)]) {
        self.IQPiker.popoverPresentationController.sourceView = self.navC.view;
    }
    
    if (self.isOriginalMap) {
        [self.navC presentViewController:self.IQPiker animated:YES completion:nil];
    }
    else
    {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self.navC presentViewController:self.imagePicker animated:YES completion:nil];
    }
    return;
}

// 选择默认照片，在 客户管理-我的客户 中用到
- (void)chooseDefaultImage {
    self.img = [UIImage imageNamed:@"head_cm60"];
    if ([self respondsToSelector:@selector(returnImage:)]) {
        [self returnImage:self.img];
    }
    if (self.returnImageUrl) {
        self.returnImageUrl(@"", @"");
    }
}

//- (void)cloudActivity
//{
//    NSLog(@"从云盘上传");
//}

- (void)presentChooseImageVC:(UIImagePickerController *)imgPicker
{
    // 解决ipad闪退问题
    if ([imgPicker respondsToSelector:@selector(popoverPresentationController)]) {
        imgPicker.popoverPresentationController.sourceView = self.navC.view;
    }
    [self.navC presentViewController:imgPicker animated:YES completion:nil];
}

#pragma mark -- IQMediaPickerControllerDelegate
//当选择一张图片后进入这里 ———— 从相册选择会走此方法
- (void)mediaPickerController:(IQMediaPickerController*)controller didFinishMediaWithInfo:(NSDictionary *)info
{
    NSArray *mediaArray = [[info allValues] objectAtIndex:0];
    
    NSDictionary *dict = mediaArray[0];
    self.img = [dict objectForKey:IQMediaImage];
    self.imgName = [dict objectForKey:IQMediaFileName];
    if (self.canEditImage) {
        [self editImageWithImage];
    } else {
        [self upDataImageToService];
    }
}

#pragma mark - ImagePicker Delegate
//当选择一张图片后进入这里 ———— 相机拍照会走此方法
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.img = image;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    // 保存拍照的图片并上传
    NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    WEAKSELF
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) {
        
        ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
        
        NSString *imageName = [imageRep filename];
        if (!imageName) imageName = [NSString stringWithFormat:@"%ld.png", time(NULL)];
        weakSelf.imgName = imageName;
        if (weakSelf.canEditImage) {
            [weakSelf editImageWithImage];
        } else {
            [weakSelf upDataImageToService];
        }
    };
    if (refURL == nil) {
        [assetsLibrary writeImageToSavedPhotosAlbum:[image CGImage] metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
            if (assetURL == nil) {
                NSString *imageName = [NSString stringWithFormat:@"%ld.png", time(NULL)];
                weakSelf.imgName = imageName;
                if (weakSelf.canEditImage) {
                    [weakSelf editImageWithImage];
                } else {
                    [weakSelf upDataImageToService];
                }
            } else {
                [assetsLibrary assetForURL:assetURL resultBlock:resultblock failureBlock:nil];
            }
        }];
    } else {
        [assetsLibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)editImageWithImage
{
//    EditAvatarVC *editVC = [[EditAvatarVC alloc] init];
//    editVC.avatarImage = self.img;
//    if (self.isRectangle) editVC.isRectangle = YES;
//    WEAKSELF
//    editVC.getImage = ^(UIImage *img) {
//        weakSelf.img = img;
//        [weakSelf upDataImageToService];
//    };
//    [self.navC pushViewController:editVC animated:YES];
    
    LYLPhotoTailoringViewController *photoVC = [[LYLPhotoTailoringViewController alloc] init];
    photoVC.oldImage = self.img;
    if (self.isRectangle || self.isBannerImg) {
        photoVC.mode = PhotoMaskViewModeSquare;
    } else {
        photoVC.mode = PhotoMaskViewModeCircle;
    }
    photoVC.cropWidth = LoginVC_W;
    photoVC.cropHeight = CerPhoto_H;
    if (self.isBannerImg) {
        photoVC.cropWidth = LoginVC_W;
        photoVC.cropHeight = LoginVC_W / UI_SCREEN_WIDTH * 145.f;
    }
//    photoVC.isDark = YES;
//    photoVC.lineColor = [UIColor redColor];
    photoVC.delegate = self;
    [self.navC pushViewController:photoVC animated:YES];
}

#pragma mark - photoViewControllerDelegate
- (void)imageCropperDidCancel:(LYLPhotoTailoringViewController *)cropperViewController
{
    if (_photoType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [cropperViewController.navigationController popViewControllerAnimated:YES];
    }else{
        [cropperViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)imageCropper:(LYLPhotoTailoringViewController *)cropperViewController didFinished:(UIImage *)editedImage
{
//    WEAKSELF
//    [cropperViewController dismissViewControllerAnimated:YES completion:^{
//        weakSelf.img = editedImage;
//        [weakSelf upDataImageToService];
//    }];
    
    self.img = editedImage;
    [self upDataImageToService];
    if (_photoType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [cropperViewController.navigationController popViewControllerAnimated:YES];
    }else{
        [cropperViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - set方法
- (void)setFileType:(NSString *)fileType
{
    _fileType = fileType;
    if ([self respondsToSelector:@selector(refreshView)]) {
        [self refreshView];
    }
}

- (void)setNavC:(UINavigationController *)navC
{
    _navC = navC;
}

- (void)setParentVC:(BaseVC *)parentVC
{
    _parentVC = parentVC;
}

- (void)setParentTVC:(BaseTVC *)parentTVC
{
    _parentTVC = parentTVC;
}

- (void)returnImage:(UIImage *)image {}
- (void)refreshView {}

@end
